package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.interceptor.AdminHolder;
import com.tanhua.manage.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 验证码key前缀
    private final String MANAGE_CAP = "MANAGE_CAP_";

    // token key前缀
    private final String MANAGE_TOKEN = "MANAGE_TOKEN_";

    @Value("tanhua.secret")
    private String secret;

    //用户登录验证码图片，并将验证码上传redis业务
    public void saveCap(String uuid, String code) {
        String key = "MANAGE_CAP_" + uuid;
        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(2));
    }

    //用户登陆业务
    public ResponseEntity<Object> login(String username, String password, String verificationCode, String uuid) {

        //判空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BusinessException("用户名和密码不能为空");
        }
        //检测用户名
        Admin admin = query().eq("username", username).one();
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }

        //检测密码
        if (!SecureUtil.md5(password).equals(admin.getPassword())) {
            throw new BusinessException("输入密码不正确");
        }

        //检测验证码
        String capKey = MANAGE_CAP + uuid;
        String code = redisTemplate.opsForValue().get(capKey);
        if (StringUtils.isEmpty(verificationCode)) {
            throw new BusinessException("验证码不能为空");
        }
        if (!verificationCode.equals(code)) {
            throw new BusinessException("验证码输入不正确");
        }

        //删除验证码
        redisTemplate.delete(capKey);

        //生成token加入redis并返回
        Map<String, Object> map = new HashMap<>();
        map.put("id", username);
        map.put("password", password);

        String token = Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS256, secret).compact();

        String adminStr = JSON.toJSONString(admin);
        redisTemplate.opsForValue().set(MANAGE_TOKEN + token, adminStr,Duration.ofHours(4));

        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return ResponseEntity.ok(result);
    }

    //按token查找用户业务
    public Admin findUserByToken(String token) {
        String adminJson = redisTemplate.opsForValue().get(MANAGE_TOKEN + token);
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        if(admin == null){
            return null;
        }
        redisTemplate.opsForValue().set(MANAGE_TOKEN + token, adminJson,Duration.ofHours(4));
        return admin;
    }

    //用户基本信息业务
    public ResponseEntity<Object> showPrefile() {
        Admin admin = query().eq("id", AdminHolder.getUserId()).one();
        Map<String, String> resultMap = new HashMap<>();
        if(admin != null){
            resultMap.put("id", admin.getId().toString());
            resultMap.put("username",admin.getUsername());
            resultMap.put("avatar", admin.getAvatar());
        }
        return ResponseEntity.ok(resultMap);
    }

    //用户退出业务
    public ResponseEntity<Object> logout(String token) {
        redisTemplate.delete(MANAGE_TOKEN + token);
        return ResponseEntity.ok(null);
    }
}
